<template>
    <div class="app-container">
        <el-row :gutter="5" style="height: 100%;">
            <el-col :span="7"  style="height: 100%;">
                <el-card :style="{height:'100%' , overflow:'auto',margin: '1px',padding: '3px'}" class="interface-tree">
                        <el-form :model="queryInfParams" ref="queryInfRef" style="width: 100%">
                            <el-row style="width: 100%">
                            <el-col :span="12" style="width: 50%">
                                <el-form-item label="接口名称" prop="infName">
                                    <el-input
                                            v-model="queryInfParams.infName"
                                            placeholder="请输入接口名称"
                                            clearable
                                            @keyup.enter="handleSstInfQuery"
                                            :style="{width: '100%'}"
                                    />
                                </el-form-item>
                            </el-col>
                            <el-col :span="8">
                                <el-form-item>
                                    <el-button type="primary" icon="Search" style="margin: 3px 3px"
                                        v-hasPermi="['testmanage:infManage:all']" @click="handleSstInfQuery">搜索
                                    </el-button>
                                </el-form-item>
                            </el-col>
                        </el-row>
                    </el-form>
                    <xTable ref="configTableRef"
                            refId="configTableRef"
                            v-loading="loading2"
                            :data="sstInfList"
                            multiple="false"
                            border
                            @selection-change="handleInfSelectionChange"
                            class="tableDragger_form">
                        <template #columList>
                            <el-table-column label="接口名称" align="left" prop="infName" 
                                                :show-overflow-tooltip="true"/>
                            <el-table-column label="接口URL" align="left" prop="infUrl" v-if="false"
                                                :show-overflow-tooltip="true"/>
                            <el-table-column label="方法类型" align="center" prop="infMethod" width="75" v-if="false"
                                                :show-overflow-tooltip="true"/>
                            <el-table-column label="状态" align="center" prop="status" width="75" v-if="false"
                                                :show-overflow-tooltip="true">
                                <template #default="scope">
                                    <dict-tag :options="accStatus" :value="scope.row.status"/>
                                </template>
                            </el-table-column>
                        </template>
                    </xTable>
                    <el-row>
                        <pagination
                                style="margin:20px 0 20px 0"
                                v-show="queryInfParams.total > 0"
                                :total="queryInfParams.total"
                                v-model:page="queryInfParams.pageNum"
                                v-model:limit="queryInfParams.pageSize"
                                layout="total,pager"
                                @pagination="handleSstInfQuery"
                        />
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="17" style="position:relative;height: 100%;">
                <el-row v-if="homeOpen" style="height: 100%;">
                    <el-row>
                        <el-col :span="24">
                            <el-card :style="{height: '100%' , overflow:'auto',margin: '0px',padding: '5px'}">
                                <el-row style="margin: 10px 5px 5px 5px">
                                    <el-text class="mx-1" size="small">操作说明：</el-text>
                                    <el-row>
                                        <el-text class="mx-1" size="small">
                                            &nbsp;&nbsp;选择左侧接口后，输入参数类型、轮次、并发数，进行压测。
                                        </el-text>
                                        
                                    </el-row>
                                </el-row>
                            </el-card>
                        </el-col>
                    </el-row>
                </el-row>

                <div v-if="!homeOpen" class="api-environment-input">
                    <span style="font-size:12px" class="el-form-item__label">环境</span>
                    <baseCombox url="/tsstEnv/list"
                        valueField="envId" labelField="envName"
                        style="width: 200px"
                        :queryParam="{status: '0'}"
                        placeholder="请选择接口环境" v-model="globalEnv" />
                  <el-button
                      type="primary"
                      style="margin: 3px 3px 3px 3px"
                      icon="Edit"
                      @click="handleAddEnv"
                      v-hasPermi="['testmanage:env:insert']"
                  ></el-button>
                </div>
                <TabList v-if="!homeOpen"  v-model="tabsValue" :tabList="oneKeyTabs" nameValue="infId" :lableValue="'infName'"  @tab-remove="removeTab" class="demo-tabs page-tabs flex-cloumn" style="height:100%">
                    <template #default="{ item }">
                        <OneKeyTab :form="item" :globalEnv="globalEnv" :infOptions="infOptions" @getList="getList" :isShow="tabsValue==item.infId"></OneKeyTab>         
                    </template>
                </TabList>

            </el-col>
        </el-row>      
    </div>
</template>

<script setup name="OneKeySst">

import {computed, getCurrentInstance, nextTick, onMounted, reactive, ref, toRefs, watch} from "vue";
import OneKeyTab from '@/views/testmanage/onekeysst/component/onekeytab'
import {div, isNotVoid, isVoid, mul} from "@/utils/util";
import store from '@/store'
import {
    listInf,
    getInf,
    queryInfAll,
    querySstInfAll,
    delInf,
    addInf,
    updateInf,
    listInfExcludeChild,
} from "@/api/testmanage/sstinf";
import TabList from '@/components/TabList'
import {listDefaultEnv} from "@/api/testmanage/env";
import {useRouter} from "vue-router";

const {proxy} = getCurrentInstance();
const {sys_normal_disable, accStatus, reportStatus, reportType} = proxy.useDict("sys_normal_disable", "accStatus", "reportStatus", "reportType");

const sstInfList = ref([]);
const loading2 = ref(true);

const infOptions = ref([]);
const ws = ref();

const tabsValue = ref('')
const oneKeyTabs = ref([]);
const homeOpen = computed(() => {
    if (oneKeyTabs.value.length > 0) {
        return false
    }
    return true
});
const router = useRouter();

const globalEnv = ref('')

const bodyRow = ref((document.documentElement.clientHeight - 185) / 24)
const resultBodyRow = ref((document.documentElement.clientHeight - 185) / 25)
const jsonBodyHeight = ref(document.documentElement.clientHeight - 430 + "px");
const jsonResultHeight = ref(document.documentElement.clientHeight - 350 + "px");
const bodyHeight = ref(document.documentElement.clientHeight - 190 + "px");
const mainBodyHeight = ref(document.documentElement.clientHeight - 103 + "px");
const screenHeight = ref(document.documentElement.clientHeight - 105 + "px");
const data = reactive({
    form: {
        infCode: '',
        infName: '',
        infType: '',
        infUrl: '',
        infMethod: 'POST',
        infRequest: '',
        infEnv: '',
        contentType: 'application/json',
        authorization: '',
        autValue: 'uToken=3b89fa6880c683a49d55bd7e1ba2ea7b',
        parentId: '',
        ancestors: '',
        leader: '1',
        delFlag: '0',
        orderNum: 0,
        status: "0",
        concurrency: "10",
        round: "10",
        paramType: '',
        infResponse: '',
        infResponseJson: '',
        consumTime: '',
        success: '',
        mcs: '',
        currentMode: 'code',
        productType: '',
        calcType: '',
        optionType: '',
        reportId: '',
    },
    queryInfParams: {
        pageNum: 1,
        pageSize: 20,
        infName: undefined,
        total: 0
    },
    queryReportParams: {
        pageNum: 1,
        pageSize: 10,
        total: 0
    },
    queryParams: {
        infName: undefined
    },
    rules: {
        infCode: [{required: true, message: "接口编码不能为空", trigger: "change"}],
        productType: [{required: true, message: "产品类型不能为空", trigger: "change"}],
        calcType: [{required: true, message: "计算类型不能为空", trigger: "change"}],
        concurrency: [{required: true, message: "并发数不能为空", trigger: "change"}],
        round: [{required: true, message: "轮次不能为空", trigger: "change"}],
    },
});

const {queryParams, form, rules, queryInfParams, queryReportParams} = toRefs(data);

function reset() {
    form.value = {
        infCode: '',
        infName: '',
        infType: '',
        infUrl: '',
        infMethod: 'POST',
        infRequest: '',
        infRequestJson: '',
        infEnv: '',
        contentType: 'application/json',
        authName: '',
        authValue: 'uToken=3b89fa6880c683a49d55bd7e1ba2ea7b',
        parentId: 0,
        ancestors: '',
        leader: '1',
        delFlag: '0',
        orderNum: 0,
        status: "0",
        concurrency: "10",
        round: "10",
        paramType: '',
        infResponse: '',
        infResponseJson: '',
        success: '',
        statusCode: '',
        consumTime: '',
        mcs: '',
        currentMode: 'code',
        reportId: '',
    };
    proxy.resetForm("cataMainRef");
    proxy.resetForm("cataInfoRef");
    proxy.resetForm("infMainRef");
    proxy.resetForm("infBaseRef");
}

async function handleSstInfQuery() {
    loading2.value = true;
    await querySstInfAll(queryInfParams.value).then(response => {
        sstInfList.value = response.rows;
        queryInfParams.value.total = response.total;
        loading2.value = false;
    })
}
/**
 * 新增环境跳转
 * */
function handleAddEnv(row) {
  let url = '/pricing/Env';
  let realUrl = url.replace("/index", "")
  router.push({
    path: realUrl
  })
}
/**
 * 初始化默认环境
 * */
function getDefaultEnv() {
  let data = {'isDefault': '1'}
  listDefaultEnv(data).then(response => {
    if (response.rows.length === 1) {
      globalEnv.value = String(response.rows[0].envId);
    }
  });
}
getDefaultEnv();

/** 查询接口信息操作 */
async function queryInfDetail(row) {
    reset();
    await listInf(row.infId).then(response => {
        infOptions.value = proxy.handleTree(response.data, "infId");
        getInf(row.infId).then(response => {
            let data = Object.assign({}, response.data)
            data.infRequestJson = JSON.parse(data.infRequest);
            tabsValue.value = data.infId
            for (var i = 0; i < oneKeyTabs.value.length; i++) {
                if (oneKeyTabs.value[i].infId == tabsValue.value) {
                    return
                }
            }
            oneKeyTabs.value.push(data)
        });
    });
}

/** 选中数据 */
function handleInfSelectionChange(selection) {
    if (selection.length == 1) {
        let data = selection[0];
        queryInfDetail(data);
    }
}

function removeTab(targetValue) {
    const tabs = oneKeyTabs.value
    let activeName = tabsValue.value
    if (activeName == targetValue) {
        tabs.forEach((tab, index) => {
            if (tab.infId === targetValue) {
                const nextTab = tabs[index + 1] || tabs[index - 1]
                if (nextTab) {
                    activeName = nextTab.infId
                }
            }
        })
    }
    tabsValue.value = activeName
    oneKeyTabs.value = tabs.filter((tab) => tab.infId !== targetValue)
}

//点击分配用户按钮
onMounted(() => {
    setTimeout(() => {

    }, 300);
    window.onresize = function temp() {
        //screenHeight.value = document.documentElement.clientHeight - 350 + "px;";
    };
})

handleSstInfQuery();

</script>
<style scoped>
.el-row {
    display: flex;
    flex-wrap: wrap;
    position: relative;
    box-sizing: border-box;
    width: 100%;
}

/deep/ .jsoneditor-menu a {
    color: #3883fa !important;
    /*display: none*/
}

/deep/ .jsoneditor {
    border: thin solid #ffffff !important;

}

/deep/ .el-drawer__container {
    position: relative;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 100%;
    width: 100%;
}
</style>
<style lang="scss" scoped>
.interface-test-container{
    align-content: flex-start;
    flex-direction: column;
    flex-wrap:unset;

    &>.el-row{
        &:last-child{
            flex: 1;
        }
    }
}
.el-card {
    :deep(.el-card__body){
        height: 100%;
    }
}
.interface-tree{
    :deep(.el-card__body){
      display: flex;
      flex-direction: column;
    }
}
.demo-tabs{
    // background:red;
    :deep(>.el-tabs__header) {
        padding-right:225px;
    }
    :deep(.el-tabs__content){
        flex:1;
    }
    :deep(.el-tab-pane){
        height:100%;
        overflow:hidden;
    }
}
.api-environment-input {
  display: flex;
  align-items: center;
  position:absolute;
  right:5px;
  z-index:1;
  height:40px;
}

:deep(div.jsoneditor-outer.has-main-menu-bar)  {
    margin-bottom: -35px !important;
    padding-bottom: 35px !important;
}
</style>
